package com.android.kotlincoroutinemvvmdemo.viewmodel
import android.util.Log
import androidx.databinding.ObservableField
import com.android.kotlincoroutinemvvmdemo.bean.OneFi
import com.android.kotlincoroutinemvvmdemo.util.DataFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class OneFiViewModel : BaseViewModel() {

    private var job: Job? = null

    private val mObservableField by lazy {
        ObservableField<OneFi>()
    }

    val mOneFiFlow = MutableStateFlow<MutableList<OneFi>>(mutableListOf())

    init {
        val oneFi = OneFi("这是一个双向绑定")
        mObservableField.set(oneFi)
    }

    fun getOneFiContent(): String? = mObservableField.get()?.content

    fun setOneFiContent(content: String): String? {
        mObservableField.get()?.content = content
        Log.d(TAG, "content:${mObservableField.get()?.content}")
        return mObservableField.get()?.content
    }

    fun getOneFiDataSet() {
        job = launch {
            val dataSet = withContext(Dispatchers.IO) {
                DataFactory.createOneFi()
            }
            mOneFiFlow.value = dataSet
        }
        job?.start()
    }

    override fun onCleared() {
        super.onCleared()
        job?.cancel()
    }

    companion object {
        const val TAG = "OneFiViewModel"
    }
}